package com.wlz.learnjuc.thread;

import lombok.extern.slf4j.Slf4j;

/**
 *              死锁
 *
 *     查看死锁
 *          1.使用idea 的照相机功能
 *          2. 使用命令
 *              1） jps              # 查看java 进程
 *              2） jstack  pid（ 进程号）    # 查看 java 线程栈信息
 */
@Slf4j
public class DeadThread {
    private static String a = "a";
    private static String b = "b";

    public static void main(String[] args) {

        int i = 0;
        while (true) {
            if (i == 10) {
                deadThread();
            }
            log.info("测试死锁:{}", i++);
        }
    }

    public static void deadThread() {
        Thread threadA = new Thread(()->{
            synchronized (a) {
                System.out.println("threadA进入a同步块，执行中...");
                try {
                    Thread.sleep(2000);
                    synchronized (b) {
                        System.out.println("threadA进入b同步块，执行中...");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"threadA");

        Thread threadB = new Thread(()->{
            synchronized (b) {
                System.out.println("threadB进入b同步块，执行中...");
                synchronized (a) {
                    System.out.println("threadB进入a同步块，执行中...");
                }
            }
        },"threadB");

        threadA.start();
        threadB.start();

    }

}
